#include "server.h"
#include <QTime>

Server::Server(QObject *parent,int port)
    :QTcpServer(parent)
{
    listen(QHostAddress::Any,port);
}

void Server::incomingConnection(int socketDescriptor)
{
    TcpClientSocket *tcpClientSocket=new TcpClientSocket(this);
    connect(tcpClientSocket,SIGNAL(updateClients(QString,int)),this,SLOT(updateClients(QString,int)));
    connect(tcpClientSocket,SIGNAL(disconnected(int)),this,SLOT(slotDisconnected(int)));

    tcpClientSocket->setSocketDescriptor(socketDescriptor);

    tcpClientSocketList.append(tcpClientSocket);


    if(tcpClientSocketList.length() == 4)
    {
        vector<unsigned char> cardArray = shuffleCards();
        for(int j = 0; j < 4; j++)
        {
            QTcpSocket *s = tcpClientSocketList.at(j);
            QString info = QString("1,%1,13").arg(j);
            for(int i = 0; i < 13; i++)
            {
                QString ap = QString(",%1").arg(int(cardArray[j * 13 + i]));
                info.append(ap);
            }
            int length = info.length();
            if(s->write(info.toLatin1(),length)!=length)
            {
                continue;
            }
        }

    }




    //updateClients(info, info.length());
}

vector<unsigned char> Server::shuffleCards()
{
    const unsigned int cardNum = 52;
    vector<unsigned char> cardVec(cardNum, 0);
    for(unsigned int i = 0; i < cardNum; i++)
    {
        cardVec[i] = i;
    }
    qsrand(QTime::currentTime().msecsSinceStartOfDay());
    for(unsigned int i = 0; i < cardNum; i++)
    {
        unsigned int num = qrand() % (cardNum - i);
        qSwap(cardVec[i], cardVec[i + num]);
        //qDebug() << cardVec[i];
    }
    return cardVec;

}
void Server::updateClients(QString msg,int length)
{
    emit updateServer(msg,length);
    for(int i=0;i<tcpClientSocketList.count();i++)
    {
        QTcpSocket *item = tcpClientSocketList.at(i);
        if(item->write(msg.toLatin1(),length)!=length)
        {
            continue;
        }
    }
}

void Server::slotDisconnected(int descriptor)
{
    for(int i=0;i<tcpClientSocketList.count();i++)
    {
        QTcpSocket *item = tcpClientSocketList.at(i);
        if(item->socketDescriptor()==descriptor)
        {
            tcpClientSocketList.removeAt(i);
//            QString info = item->localAddress().toString();
//            info.append(" Disconnected");

//            ContentListWidget->addItem(info);
            return;
        }
    }
    return;
}
